
import { Injectable, NotFoundException, BadRequestException, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../system/user/user.service';
import { LoginAuthDto } from './dto/login-auth.dto';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {
  }

  //登录
  async login(dto: LoginAuthDto) {
    const { account, password } = dto

    const user = await this.userService.findByAccount(account)
    if (!user) throw new NotFoundException('账号不存在');
    const psd = await bcrypt.compare(password, user.password);

    if (!psd) throw new UnauthorizedException('密码错误');

    const payload = { id: user.id, account: user.account };

    return {
      userId: user.id,
      account: user.account,
      username: user.username,
      access_token: this.jwtService.sign(payload),
      msg: '登录成功'
    }
  }

}
